package top.lyf1210.yuwenpicturebackend.utils;

import cn.hutool.core.lang.hash.Hash;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.stereotype.Component;
import top.lyf1210.yuwenpicturebackend.config.CosClientConfig;
import top.lyf1210.yuwenpicturebackend.model.Picture;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassNameFlushPictureColor
 * @Description TODO
 * @Author钰玟
 * @Date2025/5/20 下午4:39
 * @Version 1.0
 **/
@Component
public class FlushPictureColors {

    @Resource
    private CosClientConfig cosClientConfig;
    public HashMap<Long, String> getColorList(List<Picture> pictureList , List<String> pictureUrlList) {
        HashMap<Long, String> idsColor = new HashMap<>();
        List<Long> ids = pictureList.stream().map(Picture::getId).collect(Collectors.toList());
        List<String> colors = pictureUrlList.stream().map(this::getColor).collect(Collectors.toList());
        for (int i = 0; i < ids.size(); i++) {
            idsColor.put(ids.get(i),colors.get(i));
        }
        return idsColor;
    }
    private  String getColor(String url) {

        //BucketName, Region等信息
        String bucketName = cosClientConfig.getBucket();
        String region = cosClientConfig.getRegion();
        String authString = "your-auth-string";
        // 创建请求头
        HttpRequest request = HttpUtil.createGet(url)
                .header("Host", String.format("%s.cos.%s.myqcloud.com", bucketName,region))
                .header("Date", String.valueOf(new Date())) // 自动获取当前GMT时间
                .header("Authorization", authString);

        // 发送请求并获取响应
        String picColor = "0x000000";
        HttpResponse response = request.execute();
        if(response.getStatus() == 200){
            String body = response.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            picColor = jsonObject.getStr("RGB");
            return picColor;
        }
        return picColor;
    }
}
